<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
 
/**
 * NGMenu Model
 */
class NGMenuModelNGItem extends JModelAdmin
{
	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'NGItem', $prefix = 'NGMenuTable', $config = array()) 
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		Data for the form.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	mixed	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true) 
	{
		// Get the form.
		$form = $this->loadForm('com_ngmenu.ngitem', 'ngitem', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) 
		{
			return false;
		}
		
		return $form;
	}
	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData() 
	{
		$data = $this->getItem();

		return $data;
	}
	
	public function getItem($field = null, $value = null, $getlist = false)
	{
		if ($value == null) {
			return parent::getItem($field);
		}
		
		$table = $this->getTable();
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select('*');
		$query->from($table->getTableName());
		$query->where($field . ' = ' . $value);
		$db->setQuery($query);
//		echo ($db->explain());
		if($getlist){
			return $db->loadObjectList();
		}else{
			return $db->loadObject();
		}
	}
	
	public function save($data)
	{
		return parent::save($data);
	}
	
	// update the ngitem field (menu preview individual item styles)
	public function updateField($pk='0', $fk='0', $field=null, $value=null)
	{
		$table = $this->getTable();
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->update($table->getTableName());
		$query->set($field." = '".$value."'");
		$query->where(array("id = ".$pk, "item_id = ".$fk));
		$db->setQuery($query);
		$db->query();
		return true;
	}
	
}

